package com.ruike.alisurface.services;

import android.app.Service;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.IBinder;

import com.ruike.alisurface.BuildConfig;
import com.ruike.alisurface.mqtt.MQTTService;
import com.ruike.alisurface.mqtt.ServiceUtils;
import com.ruike.alisurface.utils.APPUtils;
import com.voodoo.lib_utils.L;

import java.util.Timer;
import java.util.TimerTask;

/**
 * Author: voodoo
 * CreateDate: 2020-03-27 027 下午 03:48
 * Description: 检测APP页面是否一直运行,不运行就直接启动
 */
public class AppRunMonitoringService extends Service {

    private Timer timer = new Timer();
    private TimerTask task = new TimerTask() {
        @Override
        public void run() {
            checkIsAliveandServer();
        }
    };

    @Override
    public void onCreate() {
        super.onCreate();
        L.i("onCreate: Start monitor! ");
        timer.schedule(task, 1000, 10_000); // 设置检测的时间周期(毫秒数)
    }

    /**
     * 检测应用是否活着及mqtt 服务是否运行
     */
    private void checkIsAliveandServer() {
//        L.i("检测程序是否活着");
        int uid = APPUtils.getPackageUid(getApplicationContext(), BuildConfig.APPLICATION_ID);
        if (uid > 0) {
            if (!APPUtils.isAppRunning(getApplicationContext(), BuildConfig.APPLICATION_ID)) {
                L.e(" 检测到 软件  未启动   开始启动");
                // 指定包名的程序未在运行中
                PackageManager packageManager = getPackageManager();
                Intent intent = packageManager.getLaunchIntentForPackage(getPackageName());
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
            }
            if (!ServiceUtils.isServiceRunning(AppRunMonitoringService.this, MQTTService.class.getName())) {
                L.e(" 检测到MQTTService  未启动   开始启动");
                ServiceUtils.startService(AppRunMonitoringService.this, MQTTService.class);
            }
        } else {
            L.e("指定的APP未安装");
        }
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return START_STICKY;
    }

    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (task != null) {
            task.cancel();
        }
        if (timer != null) {
            timer.cancel();
        }
    }

}
